<?php


namespace App\Api\Helpers;



use App\Exceptions\Api\ImgAIException;
use App\Exceptions\Api\LoginException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;

class ExceptionReport
{
    public $exception;

    public $request;

    protected $report;

    function __construct(Request $request,Exception $exception)
    {
        $this->request = $request;
        $this->exception = $exception;
    }

    public $doReport = [
        AuthenticationException::class => ['未授权',401],
        LoginException::class => ['账号或密码不正确',400],
        ModelNotFoundException::class => ['该模型未找到',404],
        AuthorizationException::class => ['没有此权限',403],
        TokenInvalidException::class => ['token不合法！',499],
        ValidationException::class   => [],
        UnauthorizedHttpException::class => ['未登录或登录状态失效',422],
        NotFoundHttpException::class => ['没有找到该页面',404],
        MethodNotAllowedHttpException::class =>['访问方式不正确',405],
        QueryException::class => ['参数错误',401 ],
    ];

    public function register($className,callable $callback){
        $this->doReport[$className] = $callback;
    }

    public function shouldReturn(){
        foreach(array_keys($this->doReport) as $report){
            if ($this->exception instanceof  $report){
                $this->report = $report;
                return true;
            }
        }
        return false;
    }

    public static function make(Exception $e){
        return new static(\request(),$e);
    }

    public function report(){
        if ($this->exception instanceof ValidationException){
            $error = array_first($this->exception->errors());
            return api()->error($this->exception->status,array_first($error));
        }
        $message = $this->doReport[$this->report];
        return api()->error($message[1],$message[0]);
    }

    public function prodReport(){
        return api()->error(500,'服务器错误');
    }
}
